package com.zjitc.service.imp;

import com.zjitc.common.Gsonal;
import com.zjitc.common.ServerResponse;
import com.zjitc.common.redis.RedisCache;
import com.zjitc.dao.CategoryDao;
import com.zjitc.pojo.Category;
import com.zjitc.service.CategoryService;
import com.zjitc.utils.RedisAuto;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/14  16:03
 */
@Service
public class CategoryServiceImpl implements CategoryService {

  @Autowired
  private CategoryDao dao;

  @Autowired
  private RedisCache redis;

  private final String CATEGORYS = "categorys";

  private static final Logger log = Logger.getLogger(CarServiceImpl.class);
  private static LocalDateTime lastUpDateTime;
  private static int MAX_UPDATE_DURATION = 1000 * 3600;

  @Override
  public ServerResponse<Category> findAll() {
    if (lastUpDateTime == null) {
      RedisAuto.categoryredis(dao, redis, CATEGORYS);
      lastUpDateTime = LocalDateTime.now();
    } else {
      LocalDateTime newtime = LocalDateTime.now();
      Duration duration = Duration.between(lastUpDateTime, newtime);
      if (Math.abs(duration.toMillis()) > MAX_UPDATE_DURATION) {
        RedisAuto.categoryredis(dao, redis, CATEGORYS);
        lastUpDateTime = LocalDateTime.now();
        log.warn("update time up and to read from db");
      }
    }
    Map<String, String> stringMap = redis.hashMapGetAll(CATEGORYS);
    List<Category> categories = new ArrayList<>();
    stringMap.forEach((key, value) -> {
      Category category = Gsonal.fromJson(value, Category.class);
      categories.add(category);
    });
    return ServerResponse.createSuccess(categories);
  }


  @Override
  public List<Category> adminfindAll() {
    return dao.findAll();
  }

  @Override
  public void update(String cid, String name) {
    dao.update(cid, name);
  }

  @Override
  public void deletebycid(String cid) {
    dao.deletebycid(cid);
  }

  @Override
  public void update(Category category) {
    redis.hashset(CATEGORYS, category.getCid(), Gsonal.tojson(category));
    dao.update(category.getCid(), category.getCname());
  }

  @Override
  public int add(Category category) {
    int i = dao.add(category.getCname(), category.getCid());
    redis.hashset(CATEGORYS, category.getCid(), Gsonal.tojson(category));
    return i;
  }

}
